package com.venue.hjt.venueclass.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;


import com.venue.hjt.venueclass.R;
import com.venue.hjt.venueclass.db.SchAboutUs;
import com.venue.hjt.venueclass.model.JianjieFModel;
import com.venue.hjt.venueclass.utlis.Constant;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xqx on 2018/1/22.
 *
 */

public class TabJJFragment extends BaseFragment{
    private ViewPager viewPager_main;
    private RadioGroup radioGroup_tabs;
    private RadioButton[] arrRadioButton;
    private List<BaseFragment> totalList = new ArrayList<>();
    private JianjieFModel model;
    List<SchAboutUs> viewPagers=new ArrayList<>();
    JianjieReceiver jianjieReceiver;
    LinearLayout ll_jianjie;
    @Override
    protected void initView(View view) {
        //初始化选项卡
        model=new JianjieFModel();
        jianjieReceiver = new JianjieReceiver();
        getActivity().registerReceiver(jianjieReceiver, filter());
        radioGroup_tabs = view.findViewById(R.id.radioGroup_tabs);
        viewPager_main =  view.findViewById(R.id.viewPager_main);
        ll_jianjie =  view.findViewById(R.id.ll_jianjie);
        Log.e("ATG","tab"+viewPagers.size());
        initTabs();
//        //初始化ViewPager
        intiViewPager();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("ATG", viewPager_main.getWidth()+"");
                    }
                });
            }
        },20000);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_jianjie;
    }

    @Override
    protected void loadData() {

    }
    /**
     *  初始化书签选项卡
     */
    private void initTabs() {
        //获取我们定义的数组资源
        initviewp();
//        String[] arrTabTitles = getResources().getStringArray(
//                R.array.arrTabTitles);
        if (viewPagers.size()!=0){
            ll_jianjie.setVisibility(View.VISIBLE);
            arrRadioButton = new RadioButton[viewPagers.size()];
//        //根据我们资源数组的长度动态创建RadioButton添加到RadioGroup中
            for (int i = 0; i<viewPagers.size(); i++) {
                //动态创建RadioButton对象
                RadioButton radioButton = new RadioButton(getActivity());
                //设置文本
                radioButton.setText(viewPagers.get(i).getTitle());
                radioButton.setTextSize(26f);
                Resources resource=getResources();
                ColorStateList csl=resource.getColorStateList(R.color.selectortext);
                radioButton.setTextColor(csl);
                //设置位置
                radioButton.setGravity(Gravity.CENTER);
                Bitmap a=null;
                radioButton.setButtonDrawable(new BitmapDrawable(a));
                //通过选择器给RadioButton设置背景，包括点击时的背景和未被点击时的背景
                radioButton.setBackgroundResource(R.drawable.selector);
                // 获取屏幕宽度
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                //获取每个tag的宽度
                int eachWidth = screenWidth / viewPagers.size();
                //设置每个条目的宽度和高度，宽度就是上面得到的平均值，高度是包裹内容
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(eachWidth,
                        60);
                //给RadioButton设置宽度和高度，通过params设置
                radioButton.setLayoutParams(params);
                //把我们动态创建
                radioGroup_tabs.addView(radioButton);
                arrRadioButton[i] = radioButton;
            }
            //默认RadioButton数组的第0个位置为选中
            arrRadioButton[0].setChecked(true);
            //设置RadioGroup的点击事件
            radioGroup_tabs
                    .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            //遍历RadioGroup，如果RadioButton数组中的RadioButton的id和当前选中的id一样，就设置ViewPager的位置为
                            //该RadioButton所对应的ViewPager
                            for (int i = 0; i < radioGroup_tabs.getChildCount(); i++) {
                                if (arrRadioButton[i].getId() == checkedId) {
                                    viewPager_main.setCurrentItem(i);
                                }
                            }
                        }
                    });
        }else{
            ll_jianjie.setVisibility(View.GONE);
        }
    }
    public void initviewp(){
        viewPagers.clear();
        totalList.clear();
        List<SchAboutUs> viewPager = model.getViewPager();
        for (SchAboutUs schAboutUs:viewPager){
            Log.e("ATG","网址  "+schAboutUs.getLink());
            viewPagers.add(schAboutUs);
        }
    }
    /**
     *  初始化书签选项卡
     */

    private void initTabs1( ) {
        radioGroup_tabs.removeAllViews();
        viewPager_main.removeAllViews();
//        radioGroup_tabs = view.findViewById(R.id.radioGroup_tabs);
        //获取我们定义的数组资源
//        String[] arrTabTitles = getResources().getStringArray(
//                R.array.arrTabTitles);
        if (viewPagers.size()!=0) {
            ll_jianjie.setVisibility(View.VISIBLE);
            arrRadioButton = new RadioButton[viewPagers.size()];
            //根据我们资源数组的长度动态创建RadioButton添加到RadioGroup中
            for (int i = 0; i < viewPagers.size(); i++) {
                //动态创建RadioButton对象
                RadioButton radioButton = new RadioButton(getActivity());
                //设置文本
                radioButton.setText(viewPagers.get(i).getTitle());
                radioButton.setTextSize(26f);
                Resources resource = getResources();
                ColorStateList csl = resource.getColorStateList(R.color.selectortext);
                radioButton.setTextColor(csl);
                //设置位置
                radioButton.setGravity(Gravity.CENTER);
                Bitmap a = null;
                radioButton.setButtonDrawable(new BitmapDrawable(a));
                //通过选择器给RadioButton设置背景，包括点击时的背景和未被点击时的背景
                radioButton.setBackgroundResource(R.drawable.selector);
                // 获取屏幕宽度
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                //获取每个tag的宽度
                int eachWidth = screenWidth / viewPagers.size();
                //设置每个条目的宽度和高度，宽度就是上面得到的平均值，高度是包裹内容
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(eachWidth,
                        60);
                //给RadioButton设置宽度和高度，通过params设置
                radioButton.setLayoutParams(params);
                //把我们动态创建
                radioGroup_tabs.addView(radioButton);
                arrRadioButton[i] = radioButton;
            }
            //默认RadioButton数组的第0个位置为选中
            arrRadioButton[0].setChecked(true);
            //设置RadioGroup的点击事件
            radioGroup_tabs
                    .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            //遍历RadioGroup，如果RadioButton数组中的RadioButton的id和当前选中的id一样，就设置ViewPager的位置为
                            //该RadioButton所对应的ViewPager
                            for (int i = 0; i < radioGroup_tabs.getChildCount(); i++) {
                                if (arrRadioButton[i].getId() == checkedId) {
                                    viewPager_main.setCurrentItem(i);
                                }
                            }
                        }
                    });
        }else {
            ll_jianjie.setVisibility(View.GONE);
        }
    }
    /**
     * 初始化ViewPager
     */
    private void intiViewPager1() {
//        viewPager_main =  view.findViewById(R.id.viewPager_main);
        // 初始化数据totalList,通过RadioGroup的子类长度明确ViewPager的页数
        totalList.clear();
        for (int i = 0; i < radioGroup_tabs.getChildCount(); i++) {
            //调用DummyFragment的getInstance方法，其返回值为一个DummyFragment对象
            String[] url={"http://baidu.com","https://hao.360.cn/","https://www.btime.com/?from=gjl","http://baidu.com","https://hao.360.cn/","https://www.btime.com/?from=gjl","http://baidu.com","https://hao.360.cn/"};
            WebFragment fragment = new WebFragment(viewPagers.get(i).getLink());
            Log.e("ATG","网"+viewPagers.get(i).getLink());
            //把我们实例化的Fragment放入lists集合中
            totalList.add(fragment);
        }

        // 给ViewPager设置适配器
        viewPager_main.setAdapter(new MyPagerAdapter(
                getActivity().getSupportFragmentManager(), totalList));
        // 给ViewPager设置监听事件
        viewPager_main.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                //当页面被选中时，设置RadioButton显示下面的蓝色横线，就是我们selector选择器中定义的
                arrRadioButton[position].setChecked(true);
//                arrRadioButton[position].setTextColor(Color.parseColor("#ffffff"));
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
//                arrRadioButton[arg0].setTextColor(Color.parseColor("#000000"));
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
//                arrRadioButton[arg0].setTextColor(Color.parseColor("#000000"));
            }

        });
    }
    /**
     * 初始化ViewPager
     */
    private void intiViewPager() {
        totalList.clear();
        // 初始化数据totalList,通过RadioGroup的子类长度明确ViewPager的页数
        for (int i = 0; i < radioGroup_tabs.getChildCount(); i++) {
            //调用DummyFragment的getInstance方法，其返回值为一个DummyFragment对象
            String[] url={"http://baidu.com","https://hao.360.cn/","https://www.btime.com/?from=gjl","http://baidu.com","https://hao.360.cn/","https://www.btime.com/?from=gjl","http://baidu.com","https://hao.360.cn/"};
            WebFragment fragment = new WebFragment(viewPagers.get(i).getLink());
            //把我们实例化的Fragment放入lists集合中
            totalList.add(fragment);
        }
        // 给ViewPager设置适配器
        viewPager_main.setAdapter(new MyPagerAdapter(
                getActivity().getSupportFragmentManager(), totalList));
        // 给ViewPager设置监听事件
        viewPager_main.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                //当页面被选中时，设置RadioButton显示下面的蓝色横线，就是我们selector选择器中定义的
                arrRadioButton[position].setChecked(true);
//                arrRadioButton[position].setTextColor(Color.parseColor("#ffffff"));
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
//                arrRadioButton[arg0].setTextColor(Color.parseColor("#000000"));
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
//                arrRadioButton[arg0].setTextColor(Color.parseColor("#000000"));
            }

        });
    }
    /**
     * 创建自定义适配器
     *
     *
     */
    class MyPagerAdapter extends FragmentStatePagerAdapter {
        private List<BaseFragment> list = null;

        public MyPagerAdapter(FragmentManager fm, List<BaseFragment> list) {
            super(fm);
            this.list = list;
        }
        @Override
        public BaseFragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }
    /**
     * 广播类
     */
    private class JianjieReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case Constant.JIANJIE:
                    initviewp();
                    initTabs1();
                    intiViewPager1();

                    break;
            }
        }
    }
    /**
     * @return IntentFilter 广播
     */
    private IntentFilter filter(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.JIANJIE);
        return filter;
    }
}
